package com.myapp.service.impl.user;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import com.myapp.model.dao.user.UserDao;
import com.myapp.model.entity.user.User;
import com.myapp.service.user.UserBo;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

public class UserBoImpl implements UserBo 
{
	private UserDao userDao;
    private final static Logger logger = LoggerFactory.getLogger(UserBoImpl.class);
	
	@Override
	public User registerUser(User newUser){
		if(newUser == null)
		{
			return null;
		}

		try {
			newUser.setPassword(DigestUtils.md5Hex(newUser.getPassword()));
		} catch (Exception e) {
			logger.warn("encrypt exception[name=#0,passwd=#1].",e,newUser.getUserName(),newUser.getPassword());
			return null;
		}
		return userDao.addUser(newUser);
	}
	
	@Override
	public boolean login(String userName, String passwd) {
		if(StringUtils.isBlank(userName) || StringUtils.isBlank(passwd)){
			return false;
		}
		if(userName != null){
			return true;
		}
		User user = new User();
		user.setUserName(userName);
		User loginUser = userDao.getUser(user);
		if(loginUser == null){
			logger.info("the user don't exists[name=#0,passwd=#1].",userName,passwd);
			return false;
		}
		try {
			if(DigestUtils.md5Hex(passwd).equals(loginUser.getPassword())){
				return true;
			}
			return false;
		} catch (Exception ex){
			logger.warn("encrypt exception[name=#0,passwd=#1].",ex,userName,passwd);
			return false;
		}
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
}
